const mongoose = require('mongoose')

// 快递代取订单模型
const expressPickupSchema = new mongoose.Schema({
  // 订单基本信息
  orderId: {
    type: String,
    required: true,
    unique: true
  },
  orderNo: {
    type: String,
    required: true,
    unique: true
  },
  status: {
    type: String,
    enum: ['pending', 'accepted', 'picking', 'delivering', 'completed', 'cancelled'],
    default: 'pending'
  },
  createTime: {
    type: Date,
    default: Date.now
  },
  updateTime: {
    type: Date,
    default: Date.now
  },

  // 配送信息
  deliveryAddress: {
    type: String,
    required: true
  },
  deliveryTime: {
    type: String,
    required: true
  },

  // 物品信息
  itemSize: {
    type: String,
    required: true
  },
  pickupCode: {
    type: String,
    required: true
  },
  pickupLocation: {
    type: String,
    required: true
  },

  // 费用信息
  baseFee: {
    type: Number,
    required: true,
    default: 0
  },
  deliveryFee: {
    type: Number,
    required: true,
    default: 0
  },
  tipAmount: {
    type: Number,
    required: true,
    default: 0
  },
  totalAmount: {
    type: Number,
    required: true
  },

  // 其他选项
  selectedCoupon: {
    type: String,
    default: ''
  },
  riderGender: {
    type: String,
    default: '不限性别'
  },
  moreRequirements: {
    type: Boolean,
    default: false
  },

  // 用户信息
  userId: {
    type: String,
    required: true
  },
  userName: {
    type: String,
    required: true
  },
  userPhone: {
    type: String,
    required: true
  },

  // 骑手信息
  riderId: {
    type: String,
    default: null
  },
  riderName: {
    type: String,
    default: null
  },
  riderPhone: {
    type: String,
    default: null
  },

  // 订单备注
  remarks: {
    type: String,
    default: ''
  }
})

// 更新时间中间件
expressPickupSchema.pre('save', function(next) {
  this.updateTime = new Date()
  next()
})

// 生成订单号
expressPickupSchema.statics.generateOrderNo = function() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  return `EP${year}${month}${day}${random}`
}

// 计算总金额
expressPickupSchema.methods.calculateTotal = function() {
  this.totalAmount = this.baseFee + this.deliveryFee + this.tipAmount
  return this.totalAmount
}

module.exports = mongoose.model('ExpressPickup', expressPickupSchema)
